﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;

namespace JoystickTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        DispatcherTimer _carTimer;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Create a car "engine"
            _carTimer = new DispatcherTimer();
            _carTimer.Interval = TimeSpan.FromMilliseconds(40);
            _carTimer.Tick += _carTimer_Tick;
        }

        private void joystick_StickMove(object sender, EventArgs e)
        {
            evAngleDegree.Text = "Event angle (°): " + joystick.Angle.ToString("F0");
            evAngleDistance.Text = "Event distance: " + joystick.Distance.ToString("F0");
        }

        /// <summary>
        /// Rotate car
        /// </summary>
        private void carStick_StickMove(object sender, EventArgs e)
        {
            carTransform.Rotation = carStick.Angle;
        }

        /// <summary>
        ///  Move car (change translation)
        /// </summary>
        void _carTimer_Tick(object sender, EventArgs e)
        {
            double dx = carStick.Distance / 10.0 * Math.Sin(Math.PI * carStick.Angle / 180.0);
            if (Math.Abs(carTransform.TranslateX + dx) <= carBounds.ActualWidth / 2.0)
            {
                carTransform.TranslateX += dx;
            }
            double dy = carStick.Distance / 10.0 * Math.Cos(Math.PI * carStick.Angle / 180.0);
            if (Math.Abs(carTransform.TranslateY - dy) <= carBounds.ActualHeight / 2.0)
            {
                carTransform.TranslateY -= dy;
            }
        }

        #region Navigation

        private void Image_Tap(object sender, GestureEventArgs e)
        {
            showCarDemo.Begin();
            _carTimer.Start();
        }

        private void Image_Tap_1(object sender, GestureEventArgs e)
        {
            _carTimer.Stop();
            showDemo.Begin();
        }

        #endregion
    }
}